package es.udc.emarketapp.http.controller.actions.products;

import es.udc.emarketapp.emarket.model.product.vo.ProductVO;
import es.udc.emarketapp.emarket.model.productFacade.ProductFacade;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.struts.action.DefaultAction;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;
import org.apache.struts.actions.DownloadAction.ResourceStreamInfo;

public class ProductImageAction extends DownloadAction {

    protected StreamInfo getStreamInfo(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {


        /* Get data. */
        Long idProd = Long.parseLong(request.getParameter("idProd"));

        ProductFacade productFacade = new ProductFacade();
        byte[] img = null;
        try {
            ProductVO product = productFacade.findProductById(new Long(idProd));
            img = product.getImagen();

        } catch (Exception e) {
        }
        /*
        response.setContentType("image/jpeg");

        ByteArrayOutputStream flujoBytes = new ByteArrayOutputStream(512);

        for (int i = 0; i < img.length && img.length > 0; i++) {
        flujoBytes.write((int) img[i]);
        }
        //response.getOutputStream().write(action.getMyImageInBytes());
        //response.getOutputStream().flush();

        flujoBytes.writeTo(response.getOutputStream());

         *
         */

        String contentType = "image/jpeg";
        //String path = mapping.getParameter();
        //ServletContext application = servlet.getServletContext();


        return new ByteArrayStreamInfo(contentType, img);

    }

    protected class ByteArrayStreamInfo implements StreamInfo {

        protected String contentType;
        protected byte[] bytes;

        public ByteArrayStreamInfo(String contentType, byte[] bytes) {
            this.contentType = contentType;
            this.bytes = bytes;
        }

        public String getContentType() {
            return contentType;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(bytes);
        }
    }
    /* Do action. */
    //return mapping.findForward("Success");
    //return new ResourceStreamInfo(contentType, application, path);
    //}
}
